package com.iseastar;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.Editable;
import android.text.Selection;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.iseastar.guojiang.BeeApplication;
import com.iseastar.guojiang.app.AppCache;
import com.iseastar.guojiang.app.Intents;
import com.iseastar.guojiang.logic.AppLogic;
import com.iseastar.guojiang.model.ReqResult;
import com.iseastar.guojiang.model.ServiceTaskBean;
import com.iseastar.guojiang.passport.TaskPassportDialogActivity;
import com.shouhuobao.station.R;
import com.squareup.leakcanary.RefWatcher;
import com.umeng.analytics.MobclickAgent;

import droid.frame.Config;
import droid.frame.activity.ActivityMgr;
import droid.frame.activity.base.FrameBaseActivity;
import droid.frame.activity.title.AppTitle;
import droid.frame.activity.title.TitleMgr;
import droid.frame.push.PushInterface;
import droid.frame.ui.dialog.AppLoading;
import droid.frame.utils.Android;
import droid.frame.utils.android.DataCleanManager;

/**
 * @author coffee <br>
 * 2016-3-15下午2:54:44
 */
public abstract class BaseActivity2 extends FrameBaseActivity {

    private AppTitle appTitle;

    protected SwipeRefreshLayout mSwipeLayout;

    @SuppressLint("ResourceAsColor")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setStatusBarColor(R.color.black_25);
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void findViewById() {
        super.findViewById();
        appTitle = new TitleMgr(getContext());
        appTitle.initTitle();
        mSwipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (getApp() != null) {
            Thread.setDefaultUncaughtExceptionHandler(getApp().getUncaughtExceptionHandler());
        }
        MobclickAgent.onResume(this);
        //如果栈顶的类不是火箭侠的passport，那么去缓存中获取passport数据，进行弹出展示
        if (!ActivityMgr.getTopActivity().equals("com.iseastar.guojiang.passport.TaskPassportDialogActivity")) {
            if (!AppLogic.isEmptyForList()) {
                ServiceTaskBean bean = AppLogic.getPassportList().get(0);
                Intent intent = new Intent(getContext(), TaskPassportDialogActivity.class);
                intent.putExtra("item", bean);
                if (ActivityMgr.peek() != null) {
                    ActivityMgr.peek().startActivity(intent);
                }
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    protected void onRefreshComplete() {
        if (mSwipeLayout != null) {
            getContext().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mSwipeLayout.setRefreshing(false);
                }
            });
        }
    }

    public AppTitle getAppTitle() {
        return appTitle;
    }

    public void setAppTitle(AppTitle appTitle) {
        this.appTitle = appTitle;
    }

    public void setTitleBackground(int backgroundRes) {
        View layout = findViewById(R.id.app_title_layout);
        layout.setBackgroundResource(backgroundRes);
    }

    public void setTitleBackgroundColor(int backgroundColor) {
        View layout = findViewById(R.id.app_title_layout);
        layout.setBackgroundColor(backgroundColor);
    }

    private AppLoading loading;

    public void showLoadingDialog(final String dialogMessage) {
        getContext().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (loading != null && loading.isShowing()) {
                    loading.setMessage(dialogMessage);
                    return;
                } else {
                    loading = new AppLoading(getContext());
                    loading.setMessage(dialogMessage);
                    loading.show();
                }
            }
        });
    }

    protected void cancelLoadingDialog() {
        getContext().runOnUiThread(new Runnable() {
            public void run() {
                if (loading != null) {
                    loading.dismiss();
                }
            }
        });
    }

    public boolean isEmpty(Object str) {
        if (str == null || str.toString().trim().length() == 0 || "null".equals(str.toString().trim())) {
            return true;
        } else {
            return false;
        }
    }

    public boolean isNotEmpty(Object str) {
        return !isEmpty(str);
    }

    public void startActivity(Class<?> classActivity) {
        Intent intent = new Intent();
        intent.setClass(getContext(), classActivity);
        startActivity(intent);
    }

    public BeeApplication getApp() {
        if (super.getApplication() != null) {
            return (BeeApplication) super.getApplication();
        } else {
            return (BeeApplication) BeeApplication.getContext();
        }
    }

    /**
     * 检测是否在其他设备上进行过登录
     *
     * @param result
     * @return
     */
    public boolean checkLoginStatus(ReqResult result) {
        if (result.isSuccess()) {
            return true;
        }
        //其他设备已经登录了
        else if (result.getStatus() == 10000) {
            try {
                AppLogic.logoutDealService(getContext());
                PushInterface.logout();
            } catch (Exception e) {
                e.printStackTrace();
            }
            new DataCleanManager().cleanApplicationData(getContext(), Config.getMainDiar());
            AppCache.setUser(null);
            AppCache.setOrder(null);
            AppCache.setStationOpenInfoBean(null);
            ActivityMgr.finishAll();
            Intents.startLauncherActivity(getContext());
            return false;
        } else {
            return false;
        }
    }

    /**
     * 不比较 null对象
     *
     * @param obj1
     * @param obj2
     * @return
     */
    public boolean isEquals(Object obj1, Object obj2) {
        if (obj1 == null && obj2 == null) {
            return false;
        }
        if (obj1 != null && obj1.equals(obj2)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 移动光标到最后
     */
    public void setCursorToLast(EditText editText) {
        // 光标移动到最后
        Editable editable = editText.getEditableText();
        Selection.setSelection(editable, editable.length());
    }

//    @SuppressLint("RestrictedApi")
//    @Override
//    public void onActivityResult(int requestCode, int resultCode, Intent data) {
//        FragmentManager fm = getSupportFragmentManager();
//        int index = requestCode >> 16;
//        if (index != 0) {
//            index--;
//            if (fm.getFragments() == null || index < 0
//                    || index >= fm.getFragments().size()) {
//                Log.d("BaseActivity2", "Activity result fragment index out of range: 0x" + Integer.toHexString(requestCode));
//                return;
//            }
//            Fragment frag = fm.getFragments().get(index);
//            if (frag == null) {
//                Log.d("BaseActivity2", "Activity result no fragment exists for index: 0x"
//                        + Integer.toHexString(requestCode));
//            } else {
//                handleResult(frag, requestCode, resultCode, data);
//            }
//            return;
//        }
//        super.onActivityResult(requestCode, resultCode, data);
//    }

//    /**
//     * 递归调用，对所有子Fragement生效
//     *
//     * @param frag
//     * @param requestCode
//     * @param resultCode
//     * @param data
//     */
//    private void handleResult(Fragment frag, int requestCode, int resultCode,
//                              Intent data) {
//        frag.onActivityResult(requestCode & 0xffff, resultCode, data);
//        @SuppressLint("RestrictedApi")
//        List<Fragment> frags = frag.getChildFragmentManager().getFragments();
//        if (frags != null) {
//            for (Fragment f : frags) {
//                if (f != null)
//                    handleResult(f, requestCode, resultCode, data);
//            }
//        }
//    }

    /**
     * 修改密码的登录按钮
     *
     * @param button
     * @param enable
     */
    public void setButtonEnableStyle(Button button, boolean enable) {
        int bottom = button.getPaddingBottom();
        int top = button.getPaddingTop();
        int right = button.getPaddingRight();
        int left = button.getPaddingLeft();
        if (enable) {
            button.setBackgroundResource(R.drawable.change_btn_selector);
            button.setTextColor(getResources().getColorStateList(R.color.white));
        } else {
            button.setBackgroundResource(R.drawable.app_btn_disable);
            button.setTextColor(getResources().getColor(R.color.white));

        }
        button.setPadding(left, top, right, bottom);
    }

    /**
     * 修改密码的登录按钮
     *
     * @param button
     * @param enable
     */
    public void setCourierButtonEnableStyle(Button button, boolean enable) {
        int bottom = button.getPaddingBottom();
        int top = button.getPaddingTop();
        int right = button.getPaddingRight();
        int left = button.getPaddingLeft();
        if (enable) {
            button.setBackgroundResource(R.drawable.app_courier_press_shape);
            button.setTextColor(getResources().getColorStateList(R.color.white));
        } else {
            button.setBackgroundResource(R.drawable.app_courier_disable_shape);
            button.setTextColor(getResources().getColor(R.color.white));
        }
        button.setPadding(left, top, right, bottom);
    }

    @Override
    protected void onDestroy() {
        Android.hideSoftInput(getContext());
        RefWatcher refWatcher = BeeApplication.getRefWatcher(getApplicationContext());
        refWatcher.watch(this);
        super.onDestroy();
    }

}
